package com.forest.datachangetracker.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.forest.datachangetracker.context.AuditContext;
import com.forest.datachangetracker.entity.SysAuditLog;
import com.forest.datachangetracker.mapper.AuditLogMapper;
import com.forest.datachangetracker.service.AuditLogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

/**
 *
 * 审计日志服务实现
 *
 * @author forest
 */
@Service
public class AuditLogServiceImpl extends ServiceImpl<AuditLogMapper, SysAuditLog>
        implements AuditLogService {

    @Resource(name = "dataChangeTrackerObjectMapper")
    private ObjectMapper objectMapper;

    @Override
    public void saveAuditLog(SysAuditLog auditLog) {
        this.save(auditLog);
    }

    @Override
    public void recordAuditLog(AuditContext context, Map<String, Object> oldValues, Map<String, Object> newValues, Map<String, Object> changedFields, boolean success, Object errorMessage) {
        try {
            SysAuditLog auditLog = new SysAuditLog();
            auditLog.setOperationType(context.getOperationType().name());
            auditLog.setTargetEntity(context.getTargetEntity());
            auditLog.setTargetId(context.getTargetId());
            auditLog.setOperatorId(context.getOperatorId());
            auditLog.setOperatorName(context.getOperatorName());
            auditLog.setTenantId(context.getTenantId());
            auditLog.setOperationTime(LocalDateTime.now());
            auditLog.setClientIp(context.getClientIp());
            auditLog.setMethodName(context.getMethodName());
            auditLog.setParameters(context.getParameters());
            auditLog.setSuccess(success);
            auditLog.setBatchId(context.getBatchId());
            auditLog.setBusinessKey(context.getBusinessKey());
            auditLog.setDescription(context.getDescription());
            auditLog.setErrorMessage(ObjectUtil.isNotNull(errorMessage) ? String.valueOf(errorMessage) : "");

            if (oldValues != null) {
                auditLog.setOldValues(objectMapper.writeValueAsString(oldValues));
            }
            if (newValues != null) {
                auditLog.setNewValues(objectMapper.writeValueAsString(newValues));
            }
            if (changedFields != null) {
                auditLog.setChangedFields(objectMapper.writeValueAsString(changedFields));
            }

            this.save(auditLog);

        } catch (Exception e) {
            log.error("保存审计日志失败", e);
        }
    }
}
